

function deleteQuestionComment(type){
    var id = document.getElementById("QCid").value

    $.ajax({
        type:"POST",
        url: "admin/delete",
        contentType: "application/json",
        data:JSON.stringify({
            "id":id,
            "type":type
        }),success:function (request){
            switch (request){
                case 1:{
                    alert("删除成功")
                    break
                }case 2:{
                    alert("问题或评论不存在")
                    break
                }case 3:{
                    alert("管理员未登录!")
                    break
                }
            }
        }
    })

}

function updateProfile(){
    var name = document.getElementById("name").value
    var bio = document.getElementById("bio").value
    var picUrl = document.getElementById("userAvatarUrl").src
    $.ajax({
        type: "POST",
        url: "/user/updateMessage",
        contentType: "application/json",
        data: JSON.stringify({
            "name" : name,
            "avatarUrl" : picUrl,
            "bio" : bio
        }),
        success:function (message){
            if (message.message === "error"){
                alert("仅注册用户可以修改个人资料或登录信息错误!")
            }else {
                var oDivUpdateSuccess = document.getElementById("updateSuccess")
                oDivUpdateSuccess.style.display = "block"
            }
        },error:function (){
            alert("系统错误!")
        },
        dataType: "json"
    })
}
/**
 * 注册
 */

function register(phone, password, matchingPassword) {
    var errorMessage = document.getElementById("errorMessage")
    $.ajax({
        type: "POST",
        url: "/authorize/register",
        contentType: "application/json",
        data: JSON.stringify({
            "phone": phone,
            "password": password,
            "matchingPassword": matchingPassword,
        }), success: function (body) {
            errorMessage.innerText = "注册成功! 2秒后跳转首页"
            setTimeout("location.href = '/'", 2000)
        }, error: function (body) {
            if (body.responseJSON == null) {
                errorMessage.innerText = "用户已存在!"
            } else {
                errorMessage.innerText = body.responseJSON.message
            }
        }
    })
}

function adminLogin(account,password){

    $.ajax({
        type: "POST",
        url: "admin/login",
        contentType: "application/json",
        data: JSON.stringify({
            "account":account,
            "password":password
        }),success: function (code){
            console.log(code)
            if (code == 1){
                alert("登录成功")
            }else {
                alert("登录失败")
            }
        }
    })
}

function loginByPassword(phone, password) {
    $.ajax({
        type: "POST",
        url: "/authorize/passwordLogin",
        contentType: "application/json",
        data: JSON.stringify({
            "phone": phone,
            "password": password
        }), success: function (body) {
            window.location = "/"
        }, error: function (body) {
            alert("账号密码错误")
            console.log("error")
        }
    })
}

function updatePic() {
    var formData = new FormData();
    formData.append("image", $("#uploadImage")[0].files[0]);
    $.ajax({
        url: "/file/upload",
        type: "post",
        data: formData,
        processData: false, // 告诉jQuery不要去处理发送的数据
        contentType: false, // 告诉jQuery不要去设置Content-Type请求头
        dataType: 'text',
        success: function(data) {
            var params = JSON.parse(data)
            $("#userAvatarUrl").attr("src", params.url);

        },
        error: function(data) {
        }
    });
}


/**
 * 一级评论
 * @param editor
 */
function firstLevelComment(editor) {
    var questionId = $("#question_id").val();
    var content = JSON.stringify(editor.txt.html())
    comment2target(questionId, content);
}

/**
 * 评论
 * @param targetId
 * @param content
 */
function comment2target(targetId, content) {
    if (!content) {
        alert("不能回复空内容~~~");
        return;
    }

    $.ajax({
        type: "POST",
        url: "/comment",
        contentType: 'application/json',
        data: JSON.stringify({
            "parentId": targetId,
            "content": content,
        }),
        success: function (response) {
            if (response.code === 200) {
                window.location.reload();
            } else {
                if (response.code === 2003) {
                    var isAccepted = confirm(response.message);
                    if (isAccepted) {
                        $('#myModal').modal({});
                        // window.open("https://github.com/login/oauth/authorize?client_id=7f316909bf70d1eaa2b2&redirect_uri=" + document.location.origin + "/callback&scope=user&state=1");
                        // window.localStorage.setItem("closable", true);
                    }
                } else {
                    alert(response.message);
                }
            }
        },
        dataType: "json"
    });
}

function comment(e) {
    var commentId = e.getAttribute("data-id");
    var content = $("#input-" + commentId).val();
    comment2target(commentId, 2, content);
}

/**
 * 展开二级评论
 */
function collapseComments(e) {
    var id = e.getAttribute("data-id");
    var comments = $("#comment-" + id);

    // 获取一下二级评论的展开状态
    var collapse = e.getAttribute("data-collapse");
    if (collapse) {
        // 折叠二级评论
        comments.removeClass("in");
        e.removeAttribute("data-collapse");
        e.classList.remove("active");
    } else {
        var subCommentContainer = $("#comment-" + id);
        if (subCommentContainer.children().length != 1) {
            //展开二级评论
            comments.addClass("in");
            // 标记二级评论展开状态
            e.setAttribute("data-collapse", "in");
            e.classList.add("active");
        } else {
            $.getJSON("/comment/" + id, function (data) {
                $.each(data.data.reverse(), function (index, comment) {
                    var mediaLeftElement = $("<div/>", {
                        "class": "media-left"
                    }).append($("<img/>", {
                        "class": "media-object img-rounded",
                        "src": comment.user.avatarUrl
                    }));

                    var mediaBodyElement = $("<div/>", {
                        "class": "media-body"
                    }).append($("<h5/>", {
                        "class": "media-heading",
                        "html": comment.user.name
                    })).append($("<div/>", {
                        "html": comment.content
                    })).append($("<div/>", {
                        "class": "menu"
                    }).append($("<span/>", {
                        "class": "pull-right",
                        "html": moment(comment.gmtCreate).format('YYYY-MM-DD')
                    })));

                    var mediaElement = $("<div/>", {
                        "class": "media"
                    }).append(mediaLeftElement).append(mediaBodyElement);

                    var commentElement = $("<div/>", {
                        "class": "col-lg-12 col-md-12 col-sm-12 col-xs-12 comments"
                    }).append(mediaElement);

                    subCommentContainer.prepend(commentElement);
                });
                //展开二级评论
                comments.addClass("in");
                // 标记二级评论展开状态
                e.setAttribute("data-collapse", "in");
                e.classList.add("active");
            });
        }
    }
}

function showSelectTag() {
    $("#select-tag").show();
}

function selectTag(e) {
    var value = e.getAttribute("data-tag");
    var previous = $("#tag").val();

    if (previous) {
        var index = 0;
        var appear = false; //记录value是否已经作为一个独立的标签出现过
        while (true) {
            index = previous.indexOf(value, index); //value字符串在previous中出现的位置
            if (index == -1) break;
            //判断previous中出现的value是否是另一个标签的一部分
            //即value的前一个和后一个字符都是逗号","或者没有字符时，才说明value是一个独立的标签
            if ((index == 0 || previous.charAt(index - 1) == ",")
                && (index + value.length == previous.length || previous.charAt(index + value.length) == ",")
            ) {
                appear = true;
                break;
            }
            index++; //用于搜索下一个出现位置
        }
        if (!appear) {
            //若value没有作为一个独立的标签出现过
            $("#tag").val(previous + ',' + value);
        }
    } else {
        $("#tag").val(value);
    }
}

function questionUpload(editor) {
    var title = $('#title').val()
    var tag = $('#tag').val()
    var description = JSON.stringify(editor.txt.getJSON())
    var id = $('#id').val()
    $.ajax({
        type: "POST",
        url: "/publish",
        contentType: "application/json",
        data: JSON.stringify({
            "title": title,
            "tag": tag,
            "description": description,
            "id": id
        }),
        success: function (response) {
            if (response.code === 200) {
                window.location.href = "/"
            } else {
                alert(response.message)
            }
        },
        dataType: "json"
    })
}

function questionFirstLevelComment() {

}

function getSTSToken() {
    var sts;
    $.ajax({
        type: "GET",
        url: "upload/sts",
        contentType: "application/json",
        async:false,
        success: function (response) {
            sts = response
        },
        error: function () {

        },
        dataType: "json"
    })
    return sts;
}

async function putObject (client,data,headers) {
    try {
        // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
        // 您可以通过自定义文件名（例如exampleobject.txt）或文件完整路径（例如exampledir/exampleobject.txt）的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
        // data对象可以自定义为file对象、Blob数据或者OSS Buffer。
        const result = await client.put(
            "image/png/bender123.jpg",
            data,
            headers
        );
        console.log(result);
    } catch (e) {
        console.log(e);
    }
}

function wangEditorExample(divId) {
    // var sts = getSTSToken();
    // console.log(sts)
    // const client = new OSS({
    //     // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
    //     endpoint: 'oss-cn-shenzhen',
    //     // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
    //     accessKeyId: sts.accessKeyId,
    //     accessKeySecret: sts.accessKeySecret,
    //     // 从STS服务获取的安全令牌（SecurityToken）。
    //     stsToken: sts.stsToken,
    //     // 填写Bucket名称。
    //     bucket: 'community20220305',
    //
    // });
    // const headers = {
    //     'x-oss-object-acl': 'public-read',
    // }
    const E = window.wangEditor
    const editor = new E(divId)
    editor.config.uploadImgServer = '/file/upload'
    editor.config.uploadFileName = 'image'

    // editor.config.customUploadImg = function (resultFiles, insertImgFn){
    //
    //     putObject(client,resultFiles[0],headers)
    //     // var sts = getSTSToken()
    //     // var region =  'oss-cn-shenzhen'
    //     // var bucket = 'examplebucket'
    //     // const url = resultFiles[0]
    // }

    editor.config.uploadImgHooks = {
        // 上传图片之前
        before: function (xhr) {
            console.log(xhr)
            return true
            // 可阻止图片上传
            // return {
            //     prevent: true,
            //     msg: '需要提示给用户的错误信息'
            // }
        },
        // 图片上传并返回了结果，图片插入已成功
        success: function (xhr) {
            console.log('success', xhr)
        },
        // 图片上传并返回了结果，但图片插入时出错了
        fail: function (xhr, editor, resData) {
            console.log('fail', resData)
        },
        // 上传图片出错，一般为 http 请求的错误
        error: function (xhr, editor, resData) {
            console.log('error', xhr, resData)
        },
        // 上传图片超时
        timeout: function (xhr) {
            console.log('timeout')
        },
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function (insertImgFn, result) {
            // result 即服务端返回的接口
            console.log('customInsert')
            // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
            insertImgFn(result.url)
        }
    }
    // 或者 const editor = new E( document.getElementById('div1') )
    editor.create()
    return editor;
}

function editPublish(descriptionJsonStr, editor) {
    var strToJson = JSON.parse(descriptionJsonStr)
    editor.txt.setJSON(strToJson)


}